﻿using UnityEngine;

namespace JH
{
    public static class GetOrAddComponentRealization
    {
        /// <summary>
        /// 有某个组件则返回某个组件，没有则添加
        /// </summary>
        public static T GetOrAddComponentEm<T>(this GameObject go) where T : Component
        {
            if (go == null)
                throw new System.ArgumentNullException(nameof(go), "必须传入一个物体，才能获取或添加组件");
            var tryGet = go.GetComponent(typeof(T));
            if (tryGet != null) return (T)tryGet;

            return (T)go.AddComponent(typeof(T));
        }

        /// <summary>
        ///  T2必然是T的子类，找到T,则返回T，没有T则添加T2并返回 (T)T2
        ///  比如，物体A身上寻找Collider没有则添加BoxCollider
        /// </summary>
        public static T GetOrAddComponentEm<T, T2>(this GameObject go) where T : Component where T2 : T
        {
            if (go == null)
                throw new System.ArgumentNullException(nameof(go), "必须传入一个物体，才能获取或添加组件");
            var tryGet = go.GetComponent(typeof(T));
            if (tryGet != null) return (T)tryGet;
            return (T)go.AddComponent(typeof(T2));
        }
    }
}